/*
* Copyright (C) 2021 ~ 2022 Uniontech Technology Co., Ltd.
*
* Author:      zhangbingyi <zhangbingyi@uniontech.com>
*
* Maintainer:  zhangbingyi <zhangbingyi@uniontech.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "usbdevicedetailsdlg.h"
#include "widgets/defendertableheaderview.h"

//#include <DTitlebar>
//#include <DFontSizeManager>
//#include <DTipLabel>
//#include <DCommandLinkButton>
//#include <DFileDialog>
#include <QFileDialog>

#define DIALOG_WIDTH 684 // dialog  宽度
#define DIALOG_MINIMUM_HEIGHT 533 // dialog  高度

#define LEFT_MARGINS 20 // 左边距
#define TOP_MARGINS 0 // 上边距
#define RIGHT_MARGINS 20 // 右边距离
#define BOTTOM_MARGINS 10 // 下边距离
#define SPACING 0 // 布局间隙

#define TABLEVIEW_WIDTH 644 // tableview 宽度
#define TABLEVIEW_HEIGHT 300 // tableview 高度
#define TABLEVIEW_ROW_HEIGHT 36 // tableview 每列高度

// 设备详情页 列表 各项列数
#define USB_TIME_COL 0 // 设备详情列表 时间项列数
#define USB_STRATEGY_COL 1 // 设备详情列表 连接限制列数

#define SET_ACC_NAME(control, name) SET_ACCESS_NAME(control, USBDeviceDetailsDlg, name)

USBDeviceDetailsDlg::USBDeviceDetailsDlg(USBStorageSecurityModel *model, const USBConnectionInfo &info, QWidget *parent)
    : QFrame(parent)
    , m_usbStorageSecurityModel(model)
//    , m_blurEffect(nullptr)
    , m_titleLabel(nullptr)
    , m_headerDelegate(nullptr)
    , m_usbdetailsTable(nullptr)
    , m_standardItemModel(nullptr)
    , m_USBDeviceDetailsDelegate(nullptr)
    , m_usbInfo(info)
    , m_USBPic(nullptr)
    , m_lbTotal(nullptr)
    , m_importBtn(nullptr)
{
    SET_ACC_NAME(this, detailMainWindow);

    // 大小设置
    this->resize(DIALOG_WIDTH, DIALOG_MINIMUM_HEIGHT);
    this->setFixedWidth(DIALOG_WIDTH);
    this->setFixedHeight(DIALOG_MINIMUM_HEIGHT);
    // 设置为Dialog
    setWindowFlags(Qt::Dialog);
    // 设置为阻态
    setWindowModality(Qt::ApplicationModal);
    // 背景透明化
    //setAttribute(Qt::WA_TranslucentBackground);
    // 界面初始化
    initUI();
    // 信号槽连接
    initConnection();
    // 请求数据
    initDate();
}

USBDeviceDetailsDlg::~USBDeviceDetailsDlg()
{
    m_standardItemModel->clear();
    m_standardItemModel->deleteLater();
    m_standardItemModel = nullptr;
}

// 界面初始化
void USBDeviceDetailsDlg::initUI()
{
    // 主布局
    QVBoxLayout *mainlayout = new QVBoxLayout(this);
    setLayout(mainlayout);

//    // 设置模糊
//    m_blurEffect = new DBlurEffectWidget(this);
//    m_blurEffect->setBlendMode(DBlurEffectWidget::BehindWindowBlend);
//    // 设置模糊大小
//    m_blurEffect->resize(size());
//    m_blurEffect->lower();

    //边距离
    mainlayout->setContentsMargins(LEFT_MARGINS - 20, TOP_MARGINS, RIGHT_MARGINS - 20, BOTTOM_MARGINS - 10);
    mainlayout->setSpacing(SPACING); // 0
    QHBoxLayout *titleBarLayout = new QHBoxLayout();
    titleBarLayout->setContentsMargins(0, 0, 0, 0);

    // 右上角关闭按钮
//    DTitlebar *titlebar = new DTitlebar(this);
//    titlebar->setFixedWidth(this->width());
//    SET_ACC_NAME(titlebar, closeButton);
//    titlebar->setBackgroundTransparent(true);
//    titlebar->setMenuVisible(false);
//    titleBarLayout->addWidget(titlebar, 0, Qt::AlignRight | Qt::AlignTop);
//    mainlayout->addLayout(titleBarLayout);

    // 内容布局
    QVBoxLayout *contentLayout = new QVBoxLayout();
    contentLayout->setContentsMargins(10, 0, 10, 10);
    contentLayout->addSpacing(0);

    m_titleLabel = new QLabel(tr("Device Details"), this);
    SET_ACC_NAME(m_titleLabel, titleLabel);
    m_titleLabel->setFixedHeight(36);
//    DFontSizeManager::instance()->bind(m_titleLabel, DFontSizeManager::T6);

    // 上部
    QVBoxLayout *topLayout = new QVBoxLayout();
    topLayout->setContentsMargins(0, 0, 0, 0);
    topLayout->setSpacing(0);

    // 添加顶部组件到横向布局
    topLayout->addWidget(m_titleLabel, 0, Qt::AlignTop | Qt::AlignCenter);

    // 信息展示部分
    QHBoxLayout *infoLayout = new QHBoxLayout();
    infoLayout->setContentsMargins(20, 0, 20, 0);
    infoLayout->setSpacing(0);

    // USB图标显示
    m_USBPic = new QLabel(this);
    QIcon usbIcon = QIcon(":/icons/deepin/builtin/actions/icon_usb_96px.svg");
    SET_ACC_NAME(m_USBPic, icon)
    m_USBPic->setPixmap(usbIcon.pixmap(96, 96));

    // USB具体信息显示 -- 设备名称 序列号  产品ID 供应商ID
    QWidget *usbInfoWidget = new QWidget(this);
    SET_ACC_NAME(usbInfoWidget, usbInfoWidget);
    usbInfoWidget->setMinimumWidth(300);
    usbInfoWidget->setLayout(initUSBInfoWidgetLayout());

    infoLayout->addWidget(m_USBPic);
    infoLayout->addWidget(usbInfoWidget);
    topLayout->addLayout(infoLayout);

    contentLayout->addLayout(topLayout);
    contentLayout->addSpacing(5);

    // 中间表格布局
    QWidget *centerWidget = new QWidget(this);
    SET_ACC_NAME(centerWidget, centerWidget);
    centerWidget->setFixedHeight(TABLEVIEW_HEIGHT);
    centerWidget->setFixedWidth(TABLEVIEW_WIDTH);

    // 底部
    QHBoxLayout *bottomLayout = new QHBoxLayout;
    bottomLayout->setContentsMargins(10, 0, 10, 0);
    m_lbTotal = new QLabel(tr("Total %1 records").arg(0));
//    DFontSizeManager::instance()->bind(m_lbTotal, DFontSizeManager::T8);
    SET_ACC_NAME(m_lbTotal, tipLable);
    bottomLayout->addWidget(m_lbTotal);
    bottomLayout->addStretch(1);

    centerWidget->setLayout(initTableWidgetLayout());
    contentLayout->addWidget(centerWidget, 0, Qt::AlignCenter);

    // 添加一个导出日志
    m_importBtn = new QCommandLinkButton(tr("Export records"));
//    DFontSizeManager::instance()->bind(m_importBtn, DFontSizeManager::T8);
    SET_ACC_NAME(m_importBtn, exportButton);
    bottomLayout->addWidget(m_importBtn);
    contentLayout->addSpacing(5);
    contentLayout->addLayout(bottomLayout);

    mainlayout->addLayout(contentLayout);
}

// 信号槽连接
void USBDeviceDetailsDlg::initConnection()
{
    connect(m_usbStorageSecurityModel, SIGNAL(sendUSBDetails(const USBConnectionInfoList &)), this, SLOT(onRecvUSBDetailsConnList(const USBConnectionInfoList &)));
    connect(m_importBtn, SIGNAL(clicked(bool)), this, SLOT(exportDetailsLog()));
    connect(m_usbStorageSecurityModel, SIGNAL(notifyWhitelistDlgUpdate()), this, SLOT(updateUIStatus())); // 白名单界面是否启用状态刷新
}

// 请求数据
void USBDeviceDetailsDlg::initDate()
{
    // 向DBUS 请求数据
    m_usbStorageSecurityModel->asyncReadUSBDetails(m_usbInfo);
}

// 初始化设备4个 信息 布局
QVBoxLayout *USBDeviceDetailsDlg::initUSBInfoWidgetLayout()
{
    QVBoxLayout *outLayout = new QVBoxLayout;

    QGridLayout *gLayout = new QGridLayout;
    gLayout->setVerticalSpacing(10);

    outLayout->addStretch(1);
    outLayout->addLayout(gLayout);
    outLayout->addStretch(1);

    QWidget *usbNameItem = setLabelItem(tr("Device"), m_usbInfo.name);
    SET_ACC_NAME(usbNameItem, usbNameItem);
    QWidget *usbSerialItem = setLabelItem(tr("Serial number"), m_usbInfo.serial);
    SET_ACC_NAME(usbSerialItem, usbSerialItem);
    QWidget *usbPIDItem = setLabelItem(tr("PID"), m_usbInfo.productID);
    SET_ACC_NAME(usbPIDItem, usbPIDItem);
    QWidget *usbVIDItem = setLabelItem(tr("VID"), m_usbInfo.vendorID);
    SET_ACC_NAME(usbVIDItem, usbVIDItem);

    gLayout->addWidget(usbNameItem, 0, 0, 1, 1);
    gLayout->addWidget(usbSerialItem, 0, 1, 1, 1);
    gLayout->addWidget(usbPIDItem, 1, 0, 1, 1);
    gLayout->addWidget(usbVIDItem, 1, 1, 1, 1);

    return outLayout;
}

// 组合设备信息Item
QWidget *USBDeviceDetailsDlg::setLabelItem(const QString &str1, const QString &str2)
{
    QWidget *labelItem = new QWidget(this);
    labelItem->setFixedWidth(255); // 设置宽度为255
    labelItem->setContentsMargins(0, 0, 0, 0);

    QHBoxLayout *layout = new QHBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);

    QLabel *labelName = new QLabel(str1, this);
//    DFontSizeManager::instance()->bind(labelName, DFontSizeManager::T7);
    labelName->setFixedWidth(60);
//    labelName->setElideMode(Qt::TextElideMode::ElideMiddle);
    labelItem->setToolTip(str1);

    QLabel *content = new QLabel(str2, this);
//    DFontSizeManager::instance()->bind(content, DFontSizeManager::T8);
    content->setFixedWidth(190);
//    content->setElideMode(Qt::TextElideMode::ElideMiddle);
    content->setToolTip(str2);

    layout->addWidget(labelName, 0, Qt::AlignLeft);
    layout->addWidget(content, 1, Qt::AlignLeft);

    labelItem->setLayout(layout);
    return labelItem;
}

void USBDeviceDetailsDlg::appendDetails(const USBConnectionInfo &info)
{
    // 第1列 USB连接时间
    QString deviceTime = info.addedTime;
    QStandardItem *timeItem = new QStandardItem(deviceTime);

    // 第2列 USB 权限状态
    int trategy = info.permMode;
    QStandardItem *strategyItem = new QStandardItem;
    if (0 == trategy) {
        strategyItem->setText(tr("Read-write"));
    } else if (1 == trategy) {
        strategyItem->setText(tr("Read only"));
    } else {
        strategyItem->setText(tr("Block"));
    }

    QList<QStandardItem *> itemLst;

    // 加载到列表中
    itemLst << timeItem << strategyItem;
    // 加载到Model
    m_standardItemModel->insertRow(0, itemLst);

    // 默认排序 -- 时间排序
    m_usbdetailsTable->sortByColumn(USB_TIME_COL, Qt::SortOrder::DescendingOrder);
}

QHBoxLayout *USBDeviceDetailsDlg::initTableWidgetLayout()
{
    QHBoxLayout *layout = new QHBoxLayout;
    layout->setMargin(0);
    layout->setSpacing(0);

    QFrame *tableFrame = new QFrame(this);
    QVBoxLayout *tableLayout = new QVBoxLayout;
    tableLayout->setContentsMargins(0, 0, 0, 6);
    tableFrame->setLayout(tableLayout);

    m_usbdetailsTable = new QTableView(this);
    SET_ACC_NAME(m_usbdetailsTable, tableView);
    m_usbdetailsTable->verticalHeader()->setDefaultSectionSize(TABLEVIEW_ROW_HEIGHT);
    m_usbdetailsTable->verticalHeader()->setVisible(false);
    m_usbdetailsTable->horizontalHeader()->setStretchLastSection(true);
    m_usbdetailsTable->setSelectionBehavior(QAbstractItemView::SelectRows); // 整行选中的的方式
    m_usbdetailsTable->setSelectionMode(QAbstractItemView::SingleSelection); // 设置选中单个目标
    m_usbdetailsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // 设置禁止编辑
    m_usbdetailsTable->setFrameShape(QTableView::NoFrame); // 设置无边框
    m_usbdetailsTable->setShowGrid(false); // 设置不显示格子线

    // 设置代理
    m_USBDeviceDetailsDelegate = new USBDeviceDetailsDelegate(this);
    m_usbdetailsTable->setItemDelegate(m_USBDeviceDetailsDelegate);

    // 设置Qt模型
    m_standardItemModel = new QStandardItemModel(this);
    m_usbdetailsTable->setModel(m_standardItemModel);

    // 初始化表格设置

    // 初始化表头
    m_headerDelegate = new DefenderTableHeaderView(Qt::Horizontal, this);
    // 设置表头的行高
    m_headerDelegate->setFixedHeight(36);
    // 更换表头
    m_usbdetailsTable->setHorizontalHeader(m_headerDelegate);

    // 设置表头
    QStandardItem *item_0 = new QStandardItem(tr("Time Connected"));
    item_0->setTextAlignment(Qt::AlignLeft | Qt::AlignCenter);
    QStandardItem *item_1 = new QStandardItem(tr("Policy"));
    item_1->setTextAlignment(Qt::AlignLeft | Qt::AlignCenter);

    m_standardItemModel->setHorizontalHeaderItem(0, item_0);
    m_standardItemModel->setHorizontalHeaderItem(1, item_1);

    // 设置Model数据
    m_usbdetailsTable->setModel(m_standardItemModel);

    // 屏蔽自动排序&表头排序图标
    m_usbdetailsTable->setSortingEnabled(false);
    m_usbdetailsTable->horizontalHeader()->setSortIndicatorShown(false);

    // 设置列宽
    m_usbdetailsTable->setColumnWidth(USB_TIME_COL, 319);
    m_usbdetailsTable->setColumnWidth(USB_STRATEGY_COL, 319);

    tableLayout->addWidget(m_usbdetailsTable);
    layout->addWidget(tableFrame);
    return layout;
}

void USBDeviceDetailsDlg::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event)
    deleteLater();
}

// 接收Dbus发来的 USB设备详情页信息
void USBDeviceDetailsDlg::onRecvUSBDetailsConnList(const USBConnectionInfoList &list)
{
    for (int i = 0; i < list.size(); i++) {
        USBConnectionInfo info = list.at(i);
        appendDetails(info);
    }

    // 统计连接记录数量
    m_lbTotal->setText(tr("Total %1 records").arg(list.size()));
}

// 导出USB设备详情日志
void USBDeviceDetailsDlg::exportDetailsLog()
{
    // 当前时间戳
    QString currentTime = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");

    // 向DBUS请求数据，然后得到Dbus 导出的完成信号，将数据存到相应的路径下
    QString importPath = QFileDialog::getSaveFileName(this, tr("Save to"), QDir::homePath() + "/Desktop/" + QString("%1_%2.csv").arg(m_usbInfo.name).arg(currentTime), "*.csv");

    if (importPath.isEmpty()) {
        qDebug() << Q_FUNC_INFO << "export canceled!";
        return;
    }
    // 导出某USB设备全部连接记录  导出功能
    m_usbStorageSecurityModel->asyncGetOneDevAllConnList(importPath, m_usbInfo);
}

void USBDeviceDetailsDlg::updateUIStatus()
{
    // 刷新状态
    setEnabled(m_usbStorageSecurityModel->getUIEnableStatus());
}
